package daoJPA;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;

import entityJPA.Positioncomment;

public class JPAPositionCommentDAO implements Serializable {

	private EntityManagerFactory emf = null;

	public JPAPositionCommentDAO(EntityManagerFactory emf) {
		this.emf = emf;
	}

	public EntityManager getEntityManager() {
		return emf.createEntityManager();
	}


	public void insertPositionComment(Positioncomment pc) {
		EntityManager em = getEntityManager();

		em.getTransaction().begin();

		Positioncomment poscomm = new Positioncomment();
		poscomm.setPosition(pc.getPosition());
		poscomm.setComment(pc.getComment());
		poscomm.setUser(pc.getUser());
		em.persist(poscomm);

		em.getTransaction().commit();

	}

	public void deletePositionComment(Positioncomment pc) {
		EntityManager em = getEntityManager();

		em.getTransaction().begin();

		Positioncomment posscomm = em.find(Positioncomment.class,pc.getIdPositionComment());
		em.remove(posscomm);

		em.getTransaction().commit();

	}

	public void updatePositionComment(Positioncomment pc) {
		EntityManager em = getEntityManager();

		em.getTransaction().begin();

		Positioncomment posscomm = em.find(Positioncomment.class, pc.getIdPositionComment());
		posscomm.setComment(pc.getComment());
		em.merge(posscomm);

		em.getTransaction().commit();

	}


	public List<Positioncomment> findAll() {
		EntityManager em = getEntityManager();

		Query q = null;

		try {

			CriteriaQuery cq = em.getCriteriaBuilder().createQuery();

			cq.select(cq.from(Positioncomment.class));

			q = em.createQuery(cq);

		} catch (Exception e) {

			e.printStackTrace();

		}

		return q.getResultList();



	}


	public Positioncomment findById(int id) {

		EntityManager em = getEntityManager();

		em.getTransaction().begin();

		Positioncomment posscomm = em.find(Positioncomment.class, id);

		em.getTransaction().commit();

		return posscomm;

	}

}
